package cn.itcast.itcaststore.web.servlet.client;

import cn.itcast.itcaststore.domain.User;
import cn.itcast.itcaststore.serive.UserService;
import cn.itcast.itcaststore.serive.impl.UserServiceImpl;
import cn.itcast.itcaststore.utils.ActiveCodeUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/*
* 注册操作
* @throws javax.servlet.ServletException, IOException
*
* */
@WebServlet("/register")
public class RegisterServlet extends javax.servlet.http.HttpServlet {
    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doPost(request,response);
    }

    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //将表单提交的数据封装到JavaBean
        //2.获取数据
        //2.1获取用户填写验证码
        String verifycode = request.getParameter("verifycode");
        System.out.println(verifycode);
        Map<String, String[]> map = request.getParameterMap();
        //3.验证码校验
        HttpSession session = request.getSession();
        String  checkcode_server = (String) session.getAttribute("checkcode");
        System.out.println(checkcode_server);
        session.removeAttribute("checkcode");//确保验证码一次性
        if (!checkcode_server.equalsIgnoreCase(verifycode)){
            //验证码不正确
            //提示信息
            request.setAttribute("login_msg","验证码错误！");
            //跳转登录页面
            request.getRequestDispatcher("/index.jsp").forward(request,response);
            return;
        }
        User user=new User();
        try{
            BeanUtils.populate(user,map);
            //封装激活码
            user.setActiveCode(ActiveCodeUtils.createActiveCode());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //调用service完成注册操作
        UserService service=new UserServiceImpl();
        try {
            service.register(user);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write(e.getMessage());
            return;
        }
        //注册成功，跳转到registersuccess.jsp
        response.sendRedirect(request.getContextPath()+"/client/registersuccess.jsp");
    }
}
